package com.leyou.user.controller;

import com.leyou.common.exception.pojo.LyException;
import com.leyou.user.pojo.AddressDTO;
import com.leyou.user.pojo.User;
import com.leyou.user.pojo.UserDetail;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 校验数据是否可用
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(@PathVariable("data") String data, @PathVariable("type")Integer type){
        Boolean isCanUse = userService.checkData(data,type);
        return ResponseEntity.ok(isCanUse);
    }

    /**
     * 发送手机验证码
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCodeMsg(@RequestParam("phone") String phone){
        userService.sendCodeMsg(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册
     * BindingResult 对象要紧挨着需要被校验的对象
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        if(result.hasErrors()){
            //收集异常信息
            String errorStr = result.getFieldErrors()
                    .stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            //抛出获取异常信息
            throw new LyException(400, errorStr);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 校验用户名和密码是否正确
     */
    @GetMapping("/query")
    public ResponseEntity<User> query(
            @RequestParam("username") String username,
            @RequestParam("password") String password){
        User loginUser = userService.query(username,password);
        return ResponseEntity.ok(loginUser);
    }

    /**
     * 查询指定用户的收货地址
     * @param userId    用户id
     * @param id        地址id
     */
    @GetMapping("/address")
    public ResponseEntity<AddressDTO> findAddressById(
            @RequestParam("userId") Long userId,
            @RequestParam("id") Long id){
        AddressDTO addressDTO = userService.findAddressById(userId,id);
        return ResponseEntity.ok(addressDTO);
    }

    /**
     * 根据登录用户的userId,将页面输入的数据封装到数据库tb_user表中
     * @return
     */
    @PostMapping("/message")
    public ResponseEntity<Void> updateMsgByuserId(@RequestBody UserDetail userDetail){
        userService.updateMsgByuserId(userDetail);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();

    }
}